#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from time import sleep
import socket
import cv2 as cv   #导入模块，opencv的python模块叫cv2
import numpy as np
import array

sleep_time = 20  #20ms发送间隔
buff = bytearray(1024)
# 创建一个socket:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

def socket_connect():
    # 建立连接:
    s.connect(('192.168.66.200', 80))


def socket_send(data):
    # 发送数据:
    data[0] = 0x23  #发送命令 #
    s.send(bytes(data))

def socket_send1():
    # 发送数据:
    for data in range(100000,999999):
        text = "#:%d%d%d%d%d%d%d"%(data,data,data,data,data,data,data);
        print(text)
        s.send(text.encode('utf-8'))
        sleep(0.03)


def get_image_info(image):
    #print("type:"+type(image))
    #print("size:"+image.size)
    print("width:%s"%(image.shape[0]))
    print("height:%s"%(image.shape[1]))
    print("dtype:%s"%(image.shape[2]))
    #print("array:"+np.array(image))

def get_pixel(image,x,y):
    ret = 0x00
    if (image[y + 0][x]):
        ret |= 0x01
    if (image[y + 1][x]):
        ret |= 0x02
    if (image[y + 2][x]):
        ret |= 0x04
    if (image[y + 3][x]):
        ret |= 0x08
    if (image[y + 4][x]):
        ret |= 0x10
    if (image[y + 5][x]):
        ret |= 0x20
    if (image[y + 6][x]):
        ret |= 0x40
    if (image[y + 7][x]):
        ret |= 0x80
    return ret;


def image_send_oled(img):
    x_index = 0
    y_index = 0
    gray = cv.cvtColor(img, cv.COLOR_RGB2GRAY)
    ret, binary = cv.threshold(gray, 0, 255, cv.THRESH_BINARY | cv.THRESH_TRIANGLE)
    cv.imshow("oled", binary)
    for y in range(0,8):
        y_index = y*8
        for x in range(0, 127):
            x_index = 127*y+x
            buff[x_index] = get_pixel(binary, x, y_index)
    socket_send(buff)
    #buff[0] = 0x23
    #s.send(bytes(buff))


def pic_oled_display(dir,start,end):
    cv.namedWindow("image", cv.WINDOW_NORMAL)  # 创建窗口并显示的是图像类型#
    for index in range(start, end):
        url = dir+"/%03d.jpeg"%(index)
        print(url)
        img = cv.imread(url)
        cv.imshow("image",img)
        image_send_oled(img)
        cv.waitKey(20) #发送间隔


print(cv.__version__)
for i in range(1, 1024):
    buff[i] = 255
print("开始表演")
socket_connect()
pic_oled_display("./pic",1,6578) #播放的图片路径  图片起始 结束序号

#cv.waitKey(0)  # 等待事件触发，参数0表示永久等待
cv.destroyAllWindows()  # 释放窗口